﻿using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Math;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Reflection;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Threading.Tasks;
using static AutoMapper.Internal.CollectionMapperExpressionFactory;

namespace Coldairarrow.Business.Base_Manage
{
    /// <summary>
    ///操作OL采购需求业务逻辑
    /// </summary>
    public class OL_MultiPlatformOrdersBusiness
    {
        public IDbAccessor Db { get; set; }
        /// <summary>
        /// 操作ol采购需求对象
        /// </summary>
        public PL_OrderInterfaceBusiness _PL_OrderInterface { get; set; }

        public OL_MultiPlatformOrdersBusiness(IDbAccessor db)
        {
            this.Db = db;
            _PL_OrderInterface = new PL_OrderInterfaceBusiness();
        }

        /// <summary>
        /// 推送众包订单
        /// </summary>
        /// <param name="newItems"></param>
        /// <returns></returns>
        public async Task<string> ZB_OrdersPush(List<ZB_ReqDTO_PushOrder> items)
        {

            //返回消息列表
            List<string> msg = new List<string>();
            //是否执行同步标志
            bool isOK = true;
            HttpClient httpClient = new HttpClient();
            foreach (var item1 in items)
            {
                try
                {
                    if (!item1.attachmentOpenDTOs.IsNullOrEmpty() && item1.attachmentOpenDTOs.Count > 0)
                    {
                        var url = item1.attachmentOpenDTOs.First().base64;
                        httpClient.Url = url;
                        item1.attachmentOpenDTOs.First().base64 = await httpClient.FileRequestBase64Async();
                    }

                    //跟踪号名称异常
                    if (!item1.attachmentOpenDTOs.IsNullOrEmpty() && item1.attachmentOpenDTOs.Count > 0 && !item1.attachmentOpenDTOs.First().fileName.Contains(item1.trackingNo)) throw new Exception($"{item1.referenceNo}异常:附件名称与跟踪号不一致请检查!!");
                    ////已推送标志
                    if (!item1.ResultMsg.IsNullOrEmpty()) throw new Exception($"{item1.referenceNo}异常:已推送{item1.ResultMsg}不可再次推送!!");
                    //物流方式提示
                    if (item1.shippingMethodCode.IsNullOrEmpty()) throw new Exception($"{item1.referenceNo}异常:物流方式为空请填写!!");

                    //判断订单行是否已经推送过，如果已推送则在单号后面加上流水号，因为相同的单号无法推送
                    var orders = GlobalAssemblies.ZBPushOrderList.Where(x => x.Value == item1.referenceNo);
                    if (orders.IsNullOrEmpty() || orders.Count() == 0)
                    {
                        item1.referenceNo_before = item1.referenceNo;
                        GlobalAssemblies.ZBPushOrderList.Add(item1.referenceNo, item1.referenceNo_before);
                    }
                    else
                    {
                        int c = orders.Count() + 1;
                        item1.referenceNo_before = item1.referenceNo;
                        item1.referenceNo = item1.referenceNo + "-" + c;
                        GlobalAssemblies.ZBPushOrderList.Add(item1.referenceNo, item1.referenceNo_before);
                    }
                }
                catch (Exception ex)
                {
                    //如果有一个信息异常报错，则不做推送
                    isOK = false;
                    msg.Add(ex.Message);
                }
            }


            //执行推送
            if (isOK)
            {
                ZB_OrderB2CInterfaceBusiness ZB_OrderB2CInfoInterface = new ZB_OrderB2CInterfaceBusiness();
                //推送开始
                await ZB_OrderB2CInfoInterface.ExecuteNoQuery<ZB_ReqDTO_PushOrder>(items, ZB_OrderB2CInfoInterface.ZB_Push, ZB_OrderB2CInfoInterface.SqlDb);
                //推送完成后判断推送消息是否是正常的,并添加到返回的消息列表中
                foreach (var item1 in items)
                {
                    if (!item1.ResultMsg.IsNullOrEmpty() && !item1.ResultMsg.Contains("推送失败"))
                    {

                        msg.Add(item1.ResultMsg + "推送成功");
                    }
                    else
                    {
                        //推送失败，移除记录的单号
                        GlobalAssemblies.ZBPushOrderList.Remove(item1.referenceNo);
                        msg.Add(item1.ResultMsg);
                        item1.ResultMsg = "";
                    }
                }
                var res = items.Where(x => !x.ResultMsg.IsNullOrEmpty());
                if (!res.IsNullOrEmpty() && res.Count() > 0)
                {
                    OrderDetailInterfaceBusiness EC_orderDetailInterface = new OrderDetailInterfaceBusiness();
                    EC_orderDetailInterface.tableField = new Dictionary<string, string>();
                    EC_orderDetailInterface.tableField.Add("rowid", "RowId");
                    EC_orderDetailInterface.tableField.Add("6837d4d2a31d84c7f6cee328", "ResultMsg");
                    List<OL_RowDTO> updataData = EC_orderDetailInterface.ConvertOL_Row(res.ToList(), EC_orderDetailInterface.tableField);//需要更新的数据集合
                    EC_orderDetailInterface.ExecuteNoQuery<OL_RowDTO>(updataData, EC_orderDetailInterface.upDateOption, EC_orderDetailInterface.SqlDb);//执行更新

                }

            }


            return string.Join("=====\r\n", msg);
        }




        /// <summary>
        /// 推送众包订单
        /// </summary>
        /// <param name="newItems"></param>
        /// <returns></returns>
        public async Task<string> PL_OrdersPush(List<PL_ReqDTO_PushOrder> items)
        {

            //返回消息列表
            List<string> msg = new List<string>();
            //是否执行同步标志
            bool isOK = true;
            foreach (var item1 in items)
            {
                try
                {
                    //跟踪号名称异常
                    if (!item1.attachments.IsNullOrEmpty() && item1.attachments.Count > 0 && !item1.attachments.First().attachment_name.Contains(item1.tracking_no)) throw new Exception($"{item1.reference_code}异常:附件名称与跟踪号不一致请检查!!");
                    //已推送标志
                    if (!item1.ResultMsg.IsNullOrEmpty()) throw new Exception($"{item1.reference_code}异常:已推送{item1.ResultMsg}不可再次推送!!");
                    //物流方式提示

                    if (item1.method_code.IsNullOrEmpty()) throw new Exception($"{item1.reference_code}异常:物流方式为空请填写!!");

                    //判断订单行是否已经推送过，如果已推送则在单号后面加上流水号，因为相同的单号无法推送
                    var orders = GlobalAssemblies.PushOrderList.Where(x => x.Value == item1.reference_code);
                    if (orders.IsNullOrEmpty() || orders.Count() == 0)
                    {
                        item1.reference_code_before = item1.reference_code;
                        GlobalAssemblies.PushOrderList.Add(item1.reference_code, item1.reference_code_before);
                    }
                    else
                    {
                        int c = orders.Count() + 1;
                        item1.reference_code_before = item1.reference_code;
                        item1.reference_code = item1.reference_code + "-" + c;
                        GlobalAssemblies.PushOrderList.Add(item1.reference_code, item1.reference_code_before);
                    }


                }
                catch (Exception ex)
                {
                    //如果有一个信息异常报错，则不做推送
                    isOK = false;
                    msg.Add(ex.Message);
                }
            }


            //执行推送
            if (isOK)
            {
                //推送开始
                await _PL_OrderInterface.ExecuteNoQuery<PL_ReqDTO_PushOrder>(items, _PL_OrderInterface.PL_Push, _PL_OrderInterface.SqlDb);
                //推送完成后判断推送消息是否是正常的,并添加到返回的消息列表中
                foreach (var item1 in items)
                {
                    if (!item1.ResultMsg.IsNullOrEmpty() && item1.ResultMsg.Contains("OMS20"))
                    {

                        msg.Add(item1.ResultMsg + "推送成功");
                    }
                    else
                    {
                        //推送失败，移除记录的单号
                        GlobalAssemblies.PushOrderList.Remove(item1.reference_code);
                        msg.Add(item1.ResultMsg);
                        item1.ResultMsg = "";
                    }
                }
                var res = items.Where(x => !x.ResultMsg.IsNullOrEmpty());
                if (!res.IsNullOrEmpty() && res.Count() > 0)
                {
                    OrderDetailInterfaceBusiness EC_orderDetailInterface = new OrderDetailInterfaceBusiness();
                    EC_orderDetailInterface.tableField = new Dictionary<string, string>();
                    EC_orderDetailInterface.tableField.Add("rowid", "RowId");
                    EC_orderDetailInterface.tableField.Add("6837d4d2a31d84c7f6cee328", "ResultMsg");
                    List<OL_RowDTO> updataData = EC_orderDetailInterface.ConvertOL_Row(res.ToList(), EC_orderDetailInterface.tableField);//需要更新的数据集合
                    EC_orderDetailInterface.ExecuteNoQuery<OL_RowDTO>(updataData, EC_orderDetailInterface.upDateOption, EC_orderDetailInterface.SqlDb);//执行更新

                }

            }


            return string.Join("=====\r\n", msg);
        }



        /// <summary>
        /// 推送飞熊仓订单
        /// </summary>
        /// <param name="newItems"></param>
        /// <returns></returns>
        public async Task<string> ER_OrdersPush(List<RE_ReqDTO_Order> items)
        {

            //返回消息列表
            List<string> msg = new List<string>();
            //是否执行同步标志
            bool isOK = true;
            //产品列表
            //try
            //{

            //    List<RE_Product> prdList = await Db.GetIQueryable<RE_Product>().Where(x => !string.IsNullOrEmpty(x.ID)).ToListAsync();
            //}
            //catch (Exception EX)
            //{ 

            //Console.WriteLine(EX.Message);
            //}

            foreach (var item1 in items)
            {
                try
                {
                    //已推送标志
                    if (!item1.ResultMsg.IsNullOrEmpty()) throw new Exception($"{item1.reference_no}异常:已推送{item1.ResultMsg}不可再次推送");
                    //物流方式提示
                    if (item1.shipping_method.IsNullOrEmpty()) throw new Exception($"{item1.reference_no}异常:运输方式为空请填写");

                    //由于接口新增数据比较慢 
                    var orders = GlobalAssemblies.REPushList.Where(x => x.Value == item1.reference_no + "Order");
                    if (orders.IsNullOrEmpty() || orders.Count() == 0)
                    {
                        item1.reference_no_before = item1.reference_no;
                        GlobalAssemblies.REPushList.Add(item1.reference_no + "Order", item1.reference_no_before);
                    }
                    else
                    {
                        throw new Exception($"异常:{item1.reference_no}已推送,不可再次推送");
                    }


                }
                catch (Exception ex)
                {
                    //如果有一个信息异常报错，则不做推送
                    isOK = false;
                    msg.Add(ex.Message);
                }
            }


            //执行推送
            if (isOK)
            {


                RE_OrderInfoInterfaceBusiness rE_OrderInfoInterface = new RE_OrderInfoInterfaceBusiness();
                //推送开始
                await rE_OrderInfoInterface.ExecuteNoQuery<RE_ReqDTO_Order>(items, rE_OrderInfoInterface.RE_Create, rE_OrderInfoInterface.SqlDb);
                //推送完成后判断推送消息是否是正常的,并添加到返回的消息列表中
                foreach (var item1 in items)
                {
                    if (!item1.ResultMsg.IsNullOrEmpty() && item1.ResultMsg.Contains("ABR0"))
                    {

                        msg.Add(item1.ResultMsg + "推送成功");
                    }
                    else
                    {
                        //推送失败，移除记录的单号
                        GlobalAssemblies.REPushList.Remove(item1.reference_no + "Order");
                        msg.Add(item1.ResultMsg);
                        item1.ResultMsg = "";
                    }
                }

                var res = items.Where(x => !x.ResultMsg.IsNullOrEmpty());
                if (!res.IsNullOrEmpty() && res.Count() > 0)
                {
                    OL_EcommerceOrderInterfaceBusiness ecommerceOrderInterface = new OL_EcommerceOrderInterfaceBusiness();
                    ecommerceOrderInterface.tableField = new Dictionary<string, string>();
                    ecommerceOrderInterface.tableField.Add("rowid", "RowId");
                    ecommerceOrderInterface.tableField.Add("68ef085b3c333678d6a3df6c", "ResultMsg");
                    List<OL_RowDTO> updataData = ecommerceOrderInterface.ConvertOL_Row(res.ToList(), ecommerceOrderInterface.tableField);//需要更新的数据集合
                    ecommerceOrderInterface.ExecuteNoQuery<OL_RowDTO>(updataData, ecommerceOrderInterface.upDateOption, ecommerceOrderInterface.SqlDb);//执行更新
                }
            }


            return string.Join("=====\r\n", msg);
        }

        /// <summary>
        /// 推送飞熊仓退货
        /// </summary>
        /// <param name="newItems"></param>
        /// <returns></returns>
        public async Task<string> ER_ReturnsPush(List<RE_ReqDTO_Return> items)
        {

            //返回消息列表
            List<string> msg = new List<string>();
            //是否执行同步标志
            bool isOK = true;

            foreach (var item1 in items)
            {
                try
                {
                    //已推送标志
                    if (!item1.ResultMsg.IsNullOrEmpty()) throw new Exception($"{item1.reference_no}异常:已推送{item1.ResultMsg}不可再次推送");
                    //入库仓库
                    if (item1.warehouse_code.IsNullOrEmpty()) throw new Exception($"{item1.reference_no}异常:入库仓库为空请选择");
                    //入库仓库
                    if (item1.tracking_no.IsNullOrEmpty()) throw new Exception($"{item1.reference_no}异常:物流单号为空清填写");
                    //由于接口新增数据比较慢,将单号保存到内存做判断
                    var orders = GlobalAssemblies.REPushList.Where(x => x.Value == item1.reference_no + "Return");
                    if (orders.IsNullOrEmpty() || orders.Count() == 0)
                    {
                        GlobalAssemblies.REPushList.Add(item1.reference_no + "Return", item1.reference_no);
                    }
                    else
                    {
                        throw new Exception($"异常:{item1.reference_no}已推送,不可再次推送");
                    }


                }
                catch (Exception ex)
                {
                    //如果有一个信息异常报错，则不做推送
                    isOK = false;
                    msg.Add(ex.Message);
                }
            }


            //执行推送
            if (isOK)
            {


                RE_ReturnsInterfaceBusiness rE_OrderInfoInterface = new RE_ReturnsInterfaceBusiness();
                //推送开始
                await rE_OrderInfoInterface.ExecuteNoQuery<RE_ReqDTO_Return>(items, rE_OrderInfoInterface.RE_Create, rE_OrderInfoInterface.SqlDb);
                //推送完成后判断推送消息是否是正常的,并添加到返回的消息列表中
                foreach (var item1 in items)
                {
                    if (!item1.ResultMsg.IsNullOrEmpty() && item1.ResultMsg.Contains("RMA"))
                    {

                        msg.Add(item1.ResultMsg + "推送成功");
                    }
                    else
                    {
                        //推送失败，移除记录的单号
                        GlobalAssemblies.REPushList.Remove(item1.reference_no + "Return");
                        msg.Add(item1.ResultMsg);
                        item1.ResultMsg = "";
                    }
                }
                var res = items.Where(x => !x.ResultMsg.IsNullOrEmpty());
                if (!res.IsNullOrEmpty() && res.Count() > 0)
                {
                    OL_EcommerceReturnInterfaceBusiness ecommerceReturnInterface = new OL_EcommerceReturnInterfaceBusiness();
                    ecommerceReturnInterface.tableField = new Dictionary<string, string>();
                    ecommerceReturnInterface.tableField.Add("rowid", "RowId");
                    ecommerceReturnInterface.tableField.Add("691d78c93c440554226abfbf", "ResultMsg");
                    List<OL_RowDTO> updataData = ecommerceReturnInterface.ConvertOL_Row(res.ToList(), ecommerceReturnInterface.tableField);//需要更新的数据集合
                    ecommerceReturnInterface.ExecuteNoQuery<OL_RowDTO>(updataData, ecommerceReturnInterface.upDateOption, ecommerceReturnInterface.SqlDb);//执行更新
                }
            }


            return string.Join("=====\r\n", msg);
        }

        /// <summary>
        /// 推送易仓订单
        /// </summary>
        /// <param name="newItems"></param>
        /// <returns></returns>
        public async Task<string> EC_ReceivingPush(List<EC_ReqDTO_SyncReceiving.Biz_Content> items)
        {

            //返回消息列表
            List<string> msg = new List<string>();
            //是否执行同步标志
            bool isOK = true;
            foreach (var item1 in items)
            {
                try
                {
                    //已推送标志
                    if (!item1.ResultMsg.IsNullOrEmpty()) throw new Exception($"{item1.reference_no}异常:已推送{item1.ResultMsg}不可再次推送");
                    //订单号空提示
                    if (item1.reference_no.IsNullOrEmpty()) throw new Exception($"{item1.reference_no}异常:订单号存在空值，请检查填写");
                    //退货单为空提示
                    if (item1.tracking_number.IsNullOrEmpty()) throw new Exception($"{item1.reference_no}异常:退货物流单号为空请填写");
                    //SKU提示
                    if (item1.product_list.IsNullOrEmpty()) throw new Exception($"{item1.reference_no}异常:sku为空，请填写");
                    //判断订单行是否已经推送过，如果已推送则在单号后面加上流水号，因为相同的单号无法推送
                    //var orders = GlobalAssemblies.PushOrderList.Where(x => x.Value == item1.reference_no);
                    //if (orders.IsNullOrEmpty() || orders.Count() == 0)
                    //{
                    //    item1.RowId__before = item1.RowId;
                    //    GlobalAssemblies.PushOrderList.Add(item1.RowId, item1.RowId__before);
                    //}
                    //else
                    //{
                    //    int c = orders.Count() + 1;
                    //    item1.RowId__before = item1.RowId;
                    //    item1.reference_no = item1.reference_no + "-" + c;
                    //    GlobalAssemblies.PushOrderList.Add(item1.RowId, item1.RowId__before);
                    //}

                    item1.expected_date = item1.expected_date.ToDateTime().ToString("yyyy-MM-dd");
                }
                catch (Exception ex)
                {
                    //如果有一个信息异常报错，则不做推送
                    isOK = false;
                    msg.Add(ex.Message);
                }
            }


            //执行推送
            if (isOK)
            {
                EC_ReceivingInterfaceBusiness rE_OrderInfoInterface = new EC_ReceivingInterfaceBusiness();
                //推送开始
                await rE_OrderInfoInterface.ExecuteNoQuery<EC_ReqDTO_SyncReceiving.Biz_Content>(items, rE_OrderInfoInterface.EC_Sync, rE_OrderInfoInterface.SqlDb);
                //推送完成后判断推送消息是否是正常的,并添加到返回的消息列表中
                foreach (var item1 in items)
                {
                    if (!item1.ResultMsg.IsNullOrEmpty() && item1.ResultMsg.Contains("R"))
                    {

                        msg.Add(item1.ResultMsg + "推送成功");
                    }
                    else
                    {
                        //推送失败，移除记录的单号
                        //GlobalAssemblies.PushOrderList.Remove(item1.RowId);
                        msg.Add(item1.reference_no + ":" + item1.ResultMsg);
                        item1.ResultMsg = "";
                    }
                }

                var list = items.Where(x => !x.ResultMsg.IsNullOrEmpty());
                if (!list.IsNullOrEmpty() && list.Count() > 0)
                {
                    OL_ExchangeMagInterfaceBusiness exchangeMagInterface = new OL_ExchangeMagInterfaceBusiness();
                    exchangeMagInterface.tableField = new Dictionary<string, string>();
                    exchangeMagInterface.tableField.Add("rowid", "RowId");
                    exchangeMagInterface.tableField.Add("68f88a703c333678d6c3576b", "ResultMsg");
                    List<OL_RowDTO> updataData = exchangeMagInterface.ConvertOL_Row(list.ToList(), exchangeMagInterface.tableField);//需要更新的数据集合
                    exchangeMagInterface.ExecuteNoQuery<OL_RowDTO>(updataData, exchangeMagInterface.upDateOption, exchangeMagInterface.SqlDb);//执行更新
                }



            }


            return string.Join("=====\r\n", msg);
        }

    }
}